import 'package:flutter/material.dart';
import 'package:table_calendar/table_calendar.dart';

import '../utils/toast_utils.dart';

class CustomDatePicker extends StatefulWidget {
  // 背景颜色，默认白色
  final Color backgroundColor;
  // 标题文本，默认“选择日期”
  final String title;
  // 标题对齐方式，默认居中
  final Alignment titleAlignment;
  // 是否为区间选择
  final bool isRange;
  // 组件最大高度，默认350
  final double maxHeight;
  // 选择回调
  final Function(DateTime? start, DateTime? end)? onSelected;
  // 日期格式
  final String dateFormat;
  // 是否自动确认，默认为false（选择后直接返回）
  final bool autoConfirm;

  const CustomDatePicker({
    Key? key,
    this.backgroundColor = Colors.white,
    this.title = "选择日期",
    this.titleAlignment = Alignment.center,
    this.isRange = false,
    this.maxHeight = 350,
    this.onSelected,
    this.dateFormat = 'yyyy-MM-dd',
    this.autoConfirm = false,
  }) : super(key: key);

  @override
  State<CustomDatePicker> createState() => _CustomDatePickerState();
}

class _CustomDatePickerState extends State<CustomDatePicker> {
  DateTime? _startRangeDate;
  DateTime? _endRangeDate;
  DateTime _singleSelectedDate = DateTime.now();
  DateTime _focusedMonth = DateTime.now();
  CalendarFormat _calendarFormat = CalendarFormat.month;

  // 月份显示文本
  final List<String> _chineseMonths = [
    '一月', '二月', '三月', '四月', '五月', '六月',
    '七月', '八月', '九月', '十月', '十一月', '十二月'
  ];

  // 星期显示文本
  final List<String> _chineseWeekdays = ['一', '二', '三', '四', '五', '六', '日'];

  @override
  Widget build(BuildContext context) {
    return Container(
      constraints: BoxConstraints(maxHeight: widget.maxHeight),
      color: widget.backgroundColor,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 顶部标题栏
          Container(
            padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
            child: Row(
              mainAxisAlignment: widget.titleAlignment == Alignment.center
                  ? MainAxisAlignment.center
                  : MainAxisAlignment.start,
              children: [
                Text(
                  widget.title,
                  style: const TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ],
            ),
          ),

          // 显示已选择的日期
          // if (widget.isRange && _startRangeDate != null)
          //   Container(
          //     padding: const EdgeInsets.symmetric(vertical: 8),
          //     child: Text(
          //       '已选择: ${_formatDate(_startRangeDate!)} - ${_endRangeDate != null ? _formatDate(_endRangeDate!) : '未选择结束日期'}',
          //       style: TextStyle(color: Colors.blue),
          //     ),
          //   )
          // else if (!widget.isRange)
          //   Container(
          //     padding: const EdgeInsets.symmetric(vertical: 8),
          //     child: Text(
          //       '已选择: ${_formatDate(_singleSelectedDate)}',
          //       style: TextStyle(color: Colors.blue),
          //     ),
          //   ),

          // 可滚动的日历内容区域
          Expanded(
            child: SingleChildScrollView(
              child: TableCalendar(
                firstDay: DateTime(2000),
                lastDay: DateTime(2050),
                focusedDay: _focusedMonth,
                selectedDayPredicate: (day) => isSameDay(day, _singleSelectedDate),
                rangeStartDay: _startRangeDate,
                rangeEndDay: _endRangeDate,
                rangeSelectionMode: widget.isRange
                    ? RangeSelectionMode.toggledOn
                    : RangeSelectionMode.disabled,
                onDaySelected: (selectedDay, focusedDay) {
                  setState(() {
                    if (widget.isRange) {
                      if (_startRangeDate == null ||
                          (_startRangeDate != null && _endRangeDate != null)) {
                        // 开始新的区间选择
                        _startRangeDate = selectedDay;
                        _endRangeDate = null;
                        _singleSelectedDate = selectedDay;
                      } else if (_endRangeDate == null) {
                        // 完成区间选择
                        if (selectedDay.isAfter(_startRangeDate!)) {
                          _endRangeDate = selectedDay;
                          // 自动确认模式下，区间选择完成后直接返回
                          if (widget.autoConfirm) {
                            widget.onSelected?.call(_startRangeDate, _endRangeDate);
                            Navigator.pop(context);
                          }
                        } else {
                          // 处理开始日期大于结束日期的情况
                          ScaffoldMessenger.of(context).showSnackBar(
                              const SnackBar(content: Text('结束日期必须晚于开始日期'))
                          );
                        }
                      }
                    } else {
                      // 单选模式
                      _singleSelectedDate = selectedDay;
                      // 自动确认模式下，单选后直接返回
                      if (widget.autoConfirm) {
                        widget.onSelected?.call(_singleSelectedDate, null);
                        Navigator.pop(context);
                      }
                    }
                    _focusedMonth = focusedDay;
                  });
                },
                onRangeSelected: (startDay, endDay, focusedDay) {
                  if (widget.isRange) {
                    setState(() {
                      _startRangeDate = startDay;
                      _endRangeDate = endDay;
                      _focusedMonth = focusedDay;
                      // 自动确认模式下，区间选择完成后直接返回
                      if (widget.autoConfirm && startDay != null && endDay != null) {
                        widget.onSelected?.call(_startRangeDate, _endRangeDate);
                        Navigator.pop(context);
                      }
                    });
                  }
                },
                onPageChanged: (focusedDay) {
                  _focusedMonth = focusedDay;
                },
                calendarFormat: _calendarFormat,
                availableCalendarFormats: const {
                  CalendarFormat.month: '月',
                },

                // 自定义中文显示
                daysOfWeekHeight: 30,
                daysOfWeekStyle: DaysOfWeekStyle(
                  dowTextFormatter: (date, locale) {
                    // 将星期几转换为中文
                    return _chineseWeekdays[date.weekday - 1];
                  },
                  weekdayStyle: TextStyle(fontWeight: FontWeight.bold),
                  weekendStyle: TextStyle(fontWeight: FontWeight.bold, color: Colors.red),
                ),
                headerStyle: HeaderStyle(
                  formatButtonVisible: false,
                  titleCentered: true,
                  titleTextFormatter: (date, locale) {
                    // 将月份和年份转换为中文
                    return '${date.year}年 ${_chineseMonths[date.month - 1]}';
                  },
                ),

                calendarStyle: const CalendarStyle(
                  rangeHighlightColor: Colors.blue,
                  rangeStartDecoration: BoxDecoration(
                    color: Colors.blue,
                    shape: BoxShape.circle,
                  ),
                  rangeEndDecoration: BoxDecoration(
                    color: Colors.blue,
                    shape: BoxShape.circle,
                  ),
                  todayDecoration: BoxDecoration(
                    color: Colors.grey,
                    shape: BoxShape.circle,
                  ),
                  selectedDecoration: BoxDecoration(
                    color: Colors.blue,
                    shape: BoxShape.circle,
                  ),
                ),
              ),
            ),
          ),

          // 底部操作栏 - 只有在非自动确认模式下才显示
          if (!widget.autoConfirm)
            Container(
              padding: const EdgeInsets.all(16),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  // 取消按钮，背景为白色，文字为主题色
                  TextButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.white,
                      // foregroundColor: Theme.of(context).primaryColor,
                      foregroundColor: Colors.black,
                      //组件宽高
                      padding: const EdgeInsets.symmetric(
                          horizontal: 24,
                          vertical: 12
                      ),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10),
                        side: BorderSide(
                          // color: Theme.of(context).primaryColor
                            color: Colors.black
                        ),
                      ),
                    ),
                    onPressed: () => Navigator.pop(context),
                    child: const Text('取消'),
                  ),
                  const SizedBox(width: 16),
                  // 确定按钮，背景为白色，文字为主题色
                  ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.blue,
                      // foregroundColor: Theme.of(context).primaryColor,
                      foregroundColor: Colors.white,
                      //组件宽高
                      padding: const EdgeInsets.symmetric(
                          horizontal: 24,
                          vertical: 12
                      ),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10),
                        side: BorderSide(
                            // color: Theme.of(context).primaryColor
                            color: Colors.white
                        ),
                      ),
                    ),
                    onPressed: () {
                      if (widget.isRange) {
                        if (_startRangeDate != null && _endRangeDate != null) {
                          widget.onSelected?.call(_startRangeDate, _endRangeDate);
                          Navigator.pop(context);
                        } else {
                          Toast.show("请选择完整的日期区间");
                        }
                      } else {
                        widget.onSelected?.call(_singleSelectedDate, null);
                        Navigator.pop(context);
                      }
                    },
                    child: const Text('确定'),
                  ),
                ],
              ),
            ),
        ],
      ),
    );
  }

  String _formatDate(DateTime date) {
    return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
  }
}